package com.mnsk.generator.common.util;

import com.mnsk.generator.common.cache.GenCacheUtils;
import com.mnsk.generator.common.constant.Constants;
import com.mnsk.generator.common.constant.GenConstants;
import com.mnsk.generator.common.constant.StringConstants;
import com.mnsk.generator.domain.Table;
import com.mnsk.generator.domain.TableColumn;
import com.mnsk.generator.common.utils.DateUtils;
import com.mnsk.generator.common.utils.StringUtils;
import org.apache.velocity.VelocityContext;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * Velocity模版工具类
 * </p>
 *
 * @author admin
 * @date 2020-11-15 13:57:11
 */
public class VelocityUtils {

    /**
     * 项目空间路径
     */
    private static final String PROJECT_PATH = "main/java";
    /**
     * mybatis空间路径
     */
    private static final String MYBATIS_PATH = "main/resources/mapper";
    /**
     * html空间路径
     */
    private static final String TEMPLATES_PATH = "main/resources/templates";
    /**
     * 默认上级菜单，系统工具
     */
    private static final String DEFAULT_PARENT_MENU_ID = "3";

    /**
     * 设置模板变量信息
     *
     * @return 模板列表
     */
    public static VelocityContext prepareContext(Table table) {
        String moduleName = table.getModuleName();
        String businessName = table.getBusinessName();
        String packageName = table.getPackageName();
        String tplCategory = table.getTplCategory();
        String functionName = table.getFunctionName();

        VelocityContext velocityContext = new VelocityContext();
        velocityContext.put("tplCategory", table.getTplCategory());
        velocityContext.put("tableName", table.getTableName());
        velocityContext.put("functionName", StringUtils.isNotEmpty(functionName) ? functionName : "【请填写功能名称】");
        velocityContext.put("ClassName", table.getClassName());
        velocityContext.put("className", StringUtils.uncapitalize(table.getClassName()));
        velocityContext.put("moduleName", table.getModuleName());
        velocityContext.put("businessName", table.getBusinessName());
        velocityContext.put("basePackage", getPackagePrefix(packageName));
        velocityContext.put("packageKey", getPackageKey(packageName));
        velocityContext.put("packageName", packageName);
        velocityContext.put("author", table.getFunctionAuthor());
        velocityContext.put("datetime", DateUtils.getTime());
        velocityContext.put("tableIgnoreEnable", !table.getColumns().stream().filter(tableColumn -> tableColumn.getColumnName().equals("ORG_CODE")).findFirst().isPresent());
        //主键信息
        velocityContext.put("pkColumn", table.getPkColumn());
        //导入信息
        velocityContext.put("importList", getImportList(table));
        velocityContext.put("permissionPrefix", getPermissionPrefix(moduleName, businessName));
        velocityContext.put("columns", table.getColumns());
        //系统信息
        velocityContext.put("swaggerConfig", GenCacheUtils.getSwaggerEnable().equals(Constants.YES));
        velocityContext.put("table", table);
        if (GenConstants.TPL_SUB.equals(tplCategory)) {
            setSubVelocityContext(velocityContext, table);
        }
        return velocityContext;
    }

    public static void setSubVelocityContext(VelocityContext context, Table table) {
        Table subTable = table.getSubTable();
        String subTableName = table.getSubTableName();
        String subTableFkName = table.getSubTableFkName();
        String subClassName = table.getSubTable().getClassName();
        String subTableFkClassName = StringUtils.underlineToHump(subTableFkName);

        context.put("subTable", subTable);
        context.put("subTableName", subTableName);
        context.put("subTableFkName", subTableFkName);
        context.put("subTableFkClassName", subTableFkClassName);
        context.put("subTableFkclassName", StringUtils.uncapitalize(subTableFkClassName));
        context.put("subClassName", subClassName);
        context.put("subclassName", StringUtils.uncapitalize(subClassName));
        context.put("subImportList", getImportList(table.getSubTable()));
    }

    /**
     * 获取文件名
     */
    public static String getFileName(String template, Table table) {
        // 文件名称
        String fileName = "";
        // 包路径
        String packageName = table.getPackageName();
        // 模块名
        String moduleName = table.getModuleName();
        // 大写类名
        String className = table.getClassName();

        String javaPath = PROJECT_PATH + StringConstants.FORWARD_SLASH + StringUtils.replace(packageName, StringConstants.POINT, StringConstants.FORWARD_SLASH);
        String mybatisPath = MYBATIS_PATH;
        String htmlPath = TEMPLATES_PATH + StringConstants.FORWARD_SLASH + moduleName;
        if (template.contains(".java")) {
            fileName = StringUtils.format(template, javaPath, className);
        } else if (template.endsWith(".xml")) {
            fileName = StringUtils.format(template, mybatisPath, className);
        } else if (template.endsWith(".vue")) {
            fileName = StringUtils.format(template, htmlPath, StringUtils.uncapitalize(table.getClassName()));
        } else if (template.endsWith(".js")) {
            fileName = StringUtils.format(template, htmlPath, StringUtils.uncapitalize(table.getClassName()));
        } else if (template.endsWith(".sql")) {
            fileName = StringUtils.format(template, "", StringUtils.uncapitalize(table.getClassName()));
        } else {
            fileName = StringUtils.format(template, "", className);
        }
        return fileName;
    }

    /**
     * 获取包前缀
     *
     * @param packageName 包名称
     * @return 包前缀名称
     */
    public static String getPackagePrefix(String packageName) {
        int lastIndex = packageName.lastIndexOf(StringConstants.POINT);
        return StringUtils.substring(packageName, 0, lastIndex);
    }

    /**
     * 获取包前缀
     *
     * @param packageName 包名称
     * @return 包前缀名称
     */
    public static String getPackageKey(String packageName) {
        int lastIndex = packageName.lastIndexOf(StringConstants.POINT);
        return StringUtils.substring(packageName, lastIndex + 1);
    }

    /**
     * 根据列类型获取导入包
     *
     * @param table 业务表对象
     * @return 返回需要导入的包列表
     */
    public static Set<String> getImportList(Table table) {
        List<TableColumn> columns = table.getColumns();
        Table subTable = table.getSubTable();
        Set<String> importList = new HashSet<>();
        if (StringUtils.isNotNull(subTable)) {
            importList.add("java.util.List");
        }
        for (TableColumn column : columns) {
            if (column.isSuperColumn()) {
                continue;
            }
            if (GenConstants.TYPE_DATE.equals(column.getJavaType())) {
                importList.add("java.util.Date");
            } else if (GenConstants.TYPE_BIGDECIMAL.equals(column.getJavaType())) {
                importList.add("java.math.BigDecimal");
            }
        }
        return importList;
    }

    /**
     * 获取权限前缀
     *
     * @param moduleName   模块名称
     * @param businessName 业务名称
     * @return 返回权限前缀
     */
    public static String getPermissionPrefix(String moduleName, String businessName) {
        return StringUtils.format("{}:{}", moduleName, businessName);
    }

}
